package com.oldroid.apps.getit.ui;

import java.io.File;
import java.net.URLConnection;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.oldroid.apps.getit.R;
import com.oldroid.apps.getit.provider.DownloadsContract.Downloads;
import com.oldroid.apps.getit.provider.DownloadsContract.Tags;
import com.oldroid.apps.getit.ui.adapter.DownloadsAdapter;
import com.oldroid.apps.getit.util.AnalyticsUtils;

public class DownloadsFragment extends Fragment implements OnItemClickListener {
	private static final String TAG = "DownloadsFragment";
	private LinearLayout mLinearLayout;
	private ListView mListView;
	private TextView mTextView;
	private boolean isStarred = false;
	private static String[] PROJECTION = new String[] { Downloads._ID, Downloads.FILENAME, Downloads.URI,
			Downloads.CREATED, Downloads.MODIFIED, Downloads.TOTAL_BYTES, Downloads.STARRED, Downloads.DELETED };
	private static String[] TAGS_PROJECTION = new String[] { Tags._ID, Tags.TAG };

	public static DownloadsFragment newInstance(boolean isStarred) {
		DownloadsFragment fragment = new DownloadsFragment();
		fragment.setStarred(isStarred);
		return fragment;
	}

	public void setStarred(boolean isStarred) {
		this.isStarred = isStarred;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
		//AnalyticsUtils.getInstance(getActivity()).trackPageView("/Downloads");
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_downloads, null);

		root.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
				ViewGroup.LayoutParams.FILL_PARENT));
		mLinearLayout = (LinearLayout) root.findViewById(R.id.downloads_tagged_title);
		mListView = (ListView) root.findViewById(R.id.downloads_list);
		mTextView = (TextView) root.findViewById(R.id.downloads_empty_label);
//
//		if (getArguments().getString("tag_search") == null) {
//			mLinearLayout.setVisibility(View.GONE);
//		} else {
//			mLinearLayout.setVisibility(View.VISIBLE);
//		}
		Cursor cursor = null;
		if (isStarred) {
			cursor = getActivity().getContentResolver().query(Downloads.buildStarredUri(), PROJECTION,
					Downloads.DELETED + "=?", new String[] { "0" }, Downloads.DEFAULT_SORT);
		} else {
			cursor = getActivity().getContentResolver().query(Downloads.CONTENT_URI, PROJECTION,
					Downloads.DELETED + "=?", new String[] { "0" }, Downloads.DEFAULT_SORT);
		}
		// Cursor tags_cursor =
		// getActivity().getContentResolver().query(Downloads_Tags.CONTENT_URI,
		// projection, selection, selectionArgs, sortOrder)
		if (cursor.getCount() == 0) {
			// You haven't downloaded yet.
			// Display the float label
			mListView.setVisibility(View.GONE);
			mTextView.setVisibility(View.VISIBLE);
		} else {
			// Display the list
			mTextView.setVisibility(View.GONE);
			mListView.setVisibility(View.VISIBLE);

			// SimpleDownloadsAdapter adapter = new
			// SimpleDownloadsAdapter(getActivity(),
			// R.layout.downloads_item_row, cursor, from, to);
			// SimpleCursorAdapter tempAdapter = new
			// SimpleCursorAdapter(getActivity(), R.layout.downloads_item_row,
			// cursor, from, to);
			Cursor tagCursor = getActivity().getContentResolver().query(Tags.CONTENT_URI, TAGS_PROJECTION, null, null,
					null);

			DownloadsAdapter dwnAdapter = new DownloadsAdapter(getActivity(), cursor, tagCursor);

			mListView.setFastScrollEnabled(true); // enable fast scrolling of
													// list.
			mListView.setAdapter(dwnAdapter);
			// mListView.setAdapter(getSimpleCursorAdapter(cursor));

			// mListView.setItemsCanFocus(false);
			mListView.setItemsCanFocus(false);
			mListView.setClickable(false);
			// mListView.setOnItemClickListener(this);

		}

		return root;

	}

	/**
	 * Returns a simple cursor adapter that contains relevant data from the
	 * downloads database. Testing method only.
	 * 
	 * @return
	 */

	private SimpleCursorAdapter getSimpleCursorAdapter(Cursor c) {

		String filename = Downloads.FILENAME;
		String filepath = Downloads.URI;
		String filesize = Downloads.TOTAL_BYTES;
		String timestamp = Downloads.MODIFIED;
		// String imageview =
		// String.valueOf(R.drawable.btn_plus_one_small_default);
		//

		String[] from = { filename, filepath, filesize, timestamp };
		int[] to = { R.id.downloads_filename, R.id.downloads_fileuri, R.id.downloads_filesize, R.id.downloads_created,

		};

		return new SimpleCursorAdapter(getActivity(), R.layout.downloads_item_row, c, from, to);

	}

	private void log(String msg) {
		Log.e("DF", msg);
	}

	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long id) {

		// Cursor c = (Cursor) av.getItemAtPosition(position);
		Cursor c = getActivity().getContentResolver().query(Downloads.buildDownloadsUri(id), PROJECTION, null, null,
				null);
		// Toast.makeText(getActivity(), "CurPos = " +c.getPosition() +
		// ". Name = " + c.getString(Downloads.COLUMN_INDEX_FILENAME),
		// Toast.LENGTH_SHORT).show(); // debugging
		String filepath = c.getString(Downloads.COLUMN_INDEX_URI);

		File fp = new File(filepath);

		if (!fp.exists())
			return;

		try {
			Intent i = new Intent();
			i.setAction(Intent.ACTION_VIEW);
			i.setDataAndType(Uri.fromFile(fp), URLConnection.guessContentTypeFromName(fp.getName()));
			startActivity(i);
		} catch (ActivityNotFoundException e) {
			Toast.makeText(getActivity(), "No program capable of opening that file was found.", Toast.LENGTH_SHORT)
					.show();

		}

	}

}
